package com.hexb.smh.controller.management;

import com.hexb.core.utils.Assert;
import com.hexb.core.utils.ObjectUtils;
import com.hexb.smh.annotations.AopOperationLog;
import com.hexb.smh.entity.Commission;
import com.hexb.smh.entity.Config;
import com.hexb.smh.entity.enums.ConfigType;
import com.hexb.smh.entity.param.commission.CommissionParam;
import com.hexb.smh.entity.param.config.ConfigParam;
import com.hexb.smh.entity.view.CommissionTable;
import com.hexb.smh.errors.ErrorCodes;
import com.hexb.smh.service.ICommissionService;
import com.hexb.smh.service.IConfigService;
import com.hexb.smh.utils.AccountHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import static com.hexb.smh.utils.SmhConstant.ROLE_ADMIN;
import static com.hexb.smh.utils.SmhConstant.ROLE_SUPER_ADMIN;

/**
 * @author : hexb
 */
@RestController
@RequestMapping("/management/commission")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(value = "A6*.提成率配置", description = "Server", tags = {"A6*.提成率配置"})
@Slf4j
public class CommissionController {

    @NonNull
    final private ICommissionService commissionService;


    @ApiOperation("添加提成率")
    @AopOperationLog(name = "添加提成率")
    @RequiresRoles(value = {ROLE_SUPER_ADMIN, ROLE_ADMIN}, logical = Logical.OR)
    @PostMapping
    public int append(@RequestBody @Valid CommissionParam.CommissionInsertParam param) {
        Commission commission = param.toCommission();
        Integer id = AccountHelper.getAccount().getId();
        commission.setCreateBy(id);
        commission.setUpdateBy(id);
        return commissionService.saveOrUpdate(commission);
    }


    @ApiOperation("修改提成率(修改一个单元格)")
    @RequiresRoles(value = {ROLE_SUPER_ADMIN, ROLE_ADMIN}, logical = Logical.OR)
    @PutMapping("/{id}")
    public int update(@RequestBody @Valid CommissionParam.CommissionUpdateParam param,
                      @PathVariable("id") Integer id) {
        Commission commission = param.toCommission(id);
        Integer aid = AccountHelper.getAccount().getId();
        commission.setUpdateBy(aid);
        return commissionService.update(commission);
    }


    @ApiOperation("获取提成率动态表格内容")
    @RequiresRoles(value = {ROLE_SUPER_ADMIN, ROLE_ADMIN}, logical = Logical.OR)
    @GetMapping("/table/readOnly/{brandId}")
    public CommissionTable<?> getReadOnlyTable(@PathVariable Integer brandId) {
        return commissionService.createReadOnlyTable(brandId);
    }


    @ApiOperation("从excel导入提成率")
    @AopOperationLog(name = "导入提成率")
    @RequiresRoles(value = {ROLE_SUPER_ADMIN, ROLE_ADMIN}, logical = Logical.OR)
    @PostMapping("/import/{brandId}")
    public int importFromExcel(MultipartFile file, @PathVariable Integer brandId) {
        String fileName = file.getOriginalFilename() != null ? file.getOriginalFilename().toLowerCase() : "";
        Assert.isFalse(fileName.endsWith("xls") || fileName.endsWith("xlsx"), ErrorCodes.NOT_EXCEL_FILE);
        return commissionService.importFromExcel(file, brandId);
    }

    @ApiOperation("导出提成率表格")
    @AopOperationLog(name = "导出提成率")
    @RequiresRoles(value = {ROLE_SUPER_ADMIN, ROLE_ADMIN}, logical = Logical.OR)
    @GetMapping("/export/{brandId}")
    public void export(HttpServletResponse response, @PathVariable Integer brandId) {
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("业务员业绩提成表.xls", "utf-8"));
            ServletOutputStream os = response.getOutputStream();
            commissionService.exportExcel(os, brandId);
        } catch (IOException e) {
            log.error("获取输出流发生错误");
        }

    }

}
